<template>
  <div class="fullscreen-map">
    <!-- 地图容器 -->
    <div id="map-container" ref="mapContainer"></div>

    <!-- 右侧工具栏 -->
    <div class="toolbar" :class="{ 'collapsed': !toolbarExpanded }">
      <!-- 折叠按钮 -->
      <div class="collapse-btn" @click="toolbarExpanded = !toolbarExpanded">
        <el-icon :class="{ 'rotated': !toolbarExpanded }">
          <ArrowRight />
        </el-icon>
      </div>

      <!-- 工具栏内容 -->
      <div class="toolbar-content" v-show="toolbarExpanded">
        <!-- 用户信息 -->
        <div class="user-section">
          <el-avatar :size="40" :src="userAvatar" />
          <div class="user-info">
            <span class="username">{{ username }}</span>
          </div>
        </div>

        <!-- 工具按钮组 -->
        <div class="tool-group">
          <el-tooltip effect="dark" content="定位" placement="left">
            <el-button @click="handleLocateMe" circle>
              <el-icon><Location /></el-icon>
            </el-button>
          </el-tooltip>

          <el-tooltip effect="dark" :content="is3D ? '切换到2D' : '切换到3D'" placement="left">
            <el-button @click="toggle3D" circle>
              <el-icon><VideoCamera /></el-icon>
            </el-button>
          </el-tooltip>

          <el-tooltip effect="dark" content="放大" placement="left">
            <el-button @click="zoomIn" circle>+</el-button>
          </el-tooltip>

          <el-tooltip effect="dark" content="缩小" placement="left">
            <el-button @click="zoomOut" circle>-</el-button>
          </el-tooltip>

          <el-tooltip effect="dark" content="坐标设置" placement="left">
            <el-button @click="toggleCoordinateInput" circle>
              <el-icon><Position /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="清空标记" placement="left">
            <el-button @click="clearOverlays" circle>
              <el-icon><RefreshRight /></el-icon>
            </el-button>
          </el-tooltip>

          <el-tooltip effect="dark" content="退出登录" placement="left">
            <el-button @click="showLogoutConfirm" circle type="danger">
              <el-icon><SwitchButton /></el-icon>
            </el-button>
          </el-tooltip>
        </div>
      </div>
    </div>

    <!-- 坐标输入面板 - 显示在工具栏左侧 -->
    <div class="coordinate-panel" v-if="showCoordinateInput && toolbarExpanded">
      <div class="panel-header">
        <span>坐标设置 (WGS84)</span>
        <el-button type="text" @click="toggleCoordinateInput" icon="Close" circle />
      </div>
      <div class="panel-content">
        <el-input v-model="latitude" placeholder="纬度" />
        <el-input v-model="longitude" placeholder="经度" />
        <el-button type="primary" @click="setCenter" class="set-center-btn">设置中心点</el-button>
      </div>
    </div>
  </div>

    <!-- 确认退出对话框 -->
    <el-dialog
        v-model="logoutDialogVisible"
        title="确认退出"
        width="400px"
        :show-close="false"
        custom-class="logout-dialog"
    >
      <span>确定要退出当前账号吗？</span>
      <template #footer>
        <el-button @click="logoutDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmLogout" :loading="logoutLoading">
          确定退出
        </el-button>
      </template>
    </el-dialog>
</template>

<script>
import {convertBD09ToWGS84, convertCoordinate} from "../utils/baiduConvert.js"; // 确保引入坐标转换函数
import {
  ElButton,
  ElIcon,
  ElAvatar,
  ElDialog,
  ElInput,
  ElTooltip,
  ElMessage
} from 'element-plus'
import {
  Location,
  SwitchButton,
  VideoCamera,
  Position,
  Close,
  ArrowRight,
  RefreshRight
} from '@element-plus/icons-vue'
import auth from "../api/auth.js"

export default {
  name: 'FullScreenMap',
  components: {
    RefreshRight,
    ElButton,
    ElIcon,
    ElAvatar,
    ElDialog,
    ElInput,
    ElTooltip,
    Location,
    SwitchButton,
    VideoCamera,
    Position,
    Close,
    ArrowRight,
  },
  props: {
    username: {
      type: String,
      default: '游客'
    },
    isLoggedIn: {
      type: Boolean,
      default: false
    },
    userAvatar: {
      type: String,
      default: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
    },
    // 新增：初始中心点坐标
    initialCenter: {
      type: Object,
      default: () => ({ lng: 116.404, lat: 39.915 })
    },
    // 新增：初始缩放级别
    initialZoom: {
      type: Number,
      default: 12
    },
    markers: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      map: null,
      mapLoaded: false,
      ak: 'QpzEJBlAzqhLMTaadaFFgpTbLMRFBifS',
      is3D: false,
      latitude: '',
      longitude: '',
      logoutDialogVisible: false,
      logoutLoading: false,
      showCoordinateInput: false,
      toolbarExpanded: true, // 工具栏展开状态
      coordinatePanelTop: '50%' ,// 用于控制坐标面板垂直位置
      currentMarkers: [],
      searchMarker: null,
      localSearch: null,
      loadingPoints: false,
    }
  },
  async mounted() {
    await this.loadBaiduMap()
    this.initMap()
    this.addZoomListener();
    window.addEventListener('resize', this.handleResize)
    if (this.map) {
      this.localSearch = new BMapGL.LocalSearch(this.map, {
        renderOptions: { map: null }, // 不自动添加标记
        onSearchComplete: this.onSearchComplete
      });
    }
  },
  beforeUnmount() {
    window.removeEventListener('resize', this.handleResize)
    // 清理地图资源
    if (this.map) {
      this.map.destroy()
      this.map = null
    }
    if (this.localSearch) {
      this.localSearch.clearResults();
      this.localSearch = null;
    }
  },
  methods: {
    async loadBaiduMap() {
      if (window.BMapGL) return true

      return new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = `https://api.map.baidu.com/api?v=1.0&type=webgl&ak=${this.ak}&callback=baiduMapInit`
        script.onerror = reject

        window.baiduMapInit = () => resolve()
        document.head.appendChild(script)
      })
    },

    initMap() {
      try {
        this.map = new BMapGL.Map('map-container', {
          minZoom: 3,
          maxZoom: 19
        });

        this.map.setMapStyleV2({
          styleId: 'a1b1c1d1e1f1g1h1' // 浅色样式
        });

        const point = new BMapGL.Point(this.initialCenter.lng, this.initialCenter.lat);
        this.map.centerAndZoom(point, this.initialZoom);
        this.map.enableScrollWheelZoom(true);

        this.map.addControl(new BMapGL.ScaleControl());

        // 添加点击事件监听
        this.map.addEventListener('click', (e) => {
          this.$emit('map-click', {
            lng: e.latlng.lng,
            lat: e.latlng.lat
          });
        });

        // 添加拖动结束事件监听
        this.map.addEventListener('dragend', () => {
          this.handleViewChange(); // 调用视图变化处理方法
        });

        this.mapLoaded = true;
        this.$emit('map-loaded', this.map);
      } catch (error) {
        ElMessage.error('地图初始化失败: ' + error.message);
        console.error('BMapGL init error:', error);
      }
    },
    toggleCoordinateInput() {
      this.showCoordinateInput = !this.showCoordinateInput
      // 确保工具栏是展开状态
      if (this.showCoordinateInput) {
        this.toolbarExpanded = true
      }
      // 保持坐标面板在固定位置
      this.coordinatePanelTop = '50%'
    },

    // 修正坐标转换逻辑
    async setCenter() {
      const lat = parseFloat(this.latitude)
      const lng = parseFloat(this.longitude)

      if (!isNaN(lat) && !isNaN(lng)) {
        try {
          // 确保调用坐标转换函数
          console.log(lng,lat)
          const convertedPoint = await convertCoordinate(lng, lat)
          console.log(convertedPoint)
          if (!convertedPoint || !convertedPoint.lng || !convertedPoint.lat) {
            throw new Error('坐标转换返回无效数据')
          }

          // 使用转换后的坐标
          const point = new BMapGL.Point(convertedPoint.lng, convertedPoint.lat)
          this.map.panTo(point)
          this.map.setZoom(11)
          this.showCoordinateInput = false
          ElMessage.success('坐标设置成功')
          const marker = new BMapGL.Marker(point)
          this.map.addOverlay(marker)
          ElMessage.success('定位成功')

          // 触发中心点改变事件
          this.$emit('center-changed', convertedPoint);

          this.clearOverlays();
        } catch (error) {
          console.error('坐标转换错误:', error)
          ElMessage.warning('坐标转换失败: ' + error.message)
        }
      } else {
        ElMessage.warning('请输入有效的经纬度数值')
      }
    },

    // 修正定位逻辑，确保使用坐标转换
    handleLocateMe() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            async position => {
              const { longitude, latitude } = position.coords
              if (!longitude || !latitude) {
                ElMessage.warning('无法获取您的位置')
                return
              }
              if(longitude>=180 || latitude>=90 || longitude<=-180 || latitude<=-90){
                ElMessage.warning('请勿输入非法坐标')
                return
              }
              try {
                console.log('原始坐标:', longitude, latitude)
                // 确保调用坐标转换函数
                const convertedPoint = await convertCoordinate(longitude, latitude)

                if (!convertedPoint || !convertedPoint.lng || !convertedPoint.lat) {
                  throw new Error('坐标转换返回无效数据')
                }
                console.log('转换后的坐标:', convertedPoint)

                const point = new BMapGL.Point(convertedPoint.lng, convertedPoint.lat)
                this.map.panTo(point)
                this.map.setZoom(11)

                // 添加定位标记
                const marker = new BMapGL.Marker(point)
                this.map.addOverlay(marker)
                ElMessage.success('定位成功')

                // 触发定位事件
                this.$emit('location-found', convertedPoint)
                this.clearOverlays();
              } catch (error) {
                console.error('定位错误:', error)
                ElMessage.warning('坐标转换失败: ' + error.message)
              }
            },
            error => {
              ElMessage.warning('获取位置失败: ' + error.message)
            }
        )
      } else {
        ElMessage.warning('您的浏览器不支持地理定位')
      }
    },

    // 暴露给外部的方法：设置中心点
    setMapCenter(lng, lat) {
      if (this.map) {
        const point = new BMapGL.Point(lng, lat)
        this.map.panTo(point)
      }
    },

    // 暴露给外部的方法：添加标记
    addMarker(lng, lat, title = '', options = {}) {
      if (this.map) {
        const point = new BMapGL.Point(lng, lat);
        const marker = new BMapGL.Marker(point, options);

        // 添加点击事件显示信息
        marker.addEventListener('click', async () => {
          try {
            // 将 BD09 转换为 WGS84
            const wgsPoint = convertBD09ToWGS84(lng, lat);

            // 显示两种坐标的提示信息
            const infoContent = `
          <strong>BD09 坐标:</strong><br>
          经度: ${lng.toFixed(6)}<br>
          纬度: ${lat.toFixed(6)}<br><br>
          <strong>WGS84 坐标:</strong><br>
          经度: ${wgsPoint.lng.toFixed(6)}<br>
          纬度: ${wgsPoint.lat.toFixed(6)}
        `;

            const infoWindow = new BMapGL.InfoWindow(infoContent, {
              width: 250,
              height: 150
            });
            this.map.openInfoWindow(infoWindow, point);

            // 触发marker点击事件
            if (options.pointId) {
              this.$emit('marker-click', options.pointId);
            }
          } catch (error) {
            ElMessage.error('坐标转换失败: ' + error.message);
          }
        });

        this.map.addOverlay(marker);
        this.currentMarkers.push(marker);

        return marker;
      }
    },

    toggle3D() {
      if (this.is3D) {
        this.map.setHeading(0)
        this.map.setTilt(0)
      } else {
        this.map.setHeading(64.5)
        this.map.setTilt(73)
      }
      this.is3D = !this.is3D
    },

    zoomIn() {
      this.map.zoomIn()
    },

    zoomOut() {
      this.map.zoomOut()
    },

    handleResize() {
      if (this.map) {
        this.map.checkResize()
      }
    },

    showLogoutConfirm() {
      this.logoutDialogVisible = true
    },

    confirmLogout() {
      this.logoutLoading = true
      setTimeout(() => {
        this.logoutLoading = false
        this.logoutDialogVisible = false
        this.performLogout()
      }, 800)
    },

    performLogout() {
      // 触发退出登录事件，由父组件处理
      this.$emit('logout')
    },
    // 获取当前地图边界
    getMapBounds() {
      if (!this.map) return null;
      const bounds = this.map.getBounds();
      return {
        swLng: bounds.getSouthWest().lng,
        swLat: bounds.getSouthWest().lat,
        neLng: bounds.getNorthEast().lng,
        neLat: bounds.getNorthEast().lat
      };
    },
    // 添加缩放事件监听
    addZoomListener() {
      if (this.map) {
        this.map.addEventListener('zoomend', () => {
          this.handleZoomChange();
        });
      }
    },

    // 处理缩放变化
    async handleZoomChange() {


      const zoom = this.map.getZoom();
      const bounds = this.getMapBounds();

      this.clearOverlays();

      if (zoom > 15 && bounds) {
        this.loadingPoints = true;
        console.log('请求参数:', {
          minX: bounds.swLng,
          minY: bounds.swLat,
          maxX: bounds.neLng,
          maxY: bounds.neLat
        });
        try {
          let response;
          if (this.$route.path !== '/map' && this.$route.path === '/home/userDistribution') {
            response = await auth.getPointsCommunity(
                bounds.swLng,
                bounds.swLat,
                bounds.neLng,
                bounds.neLat
            );
          }
          else {
            response = await auth.getPoints(
                bounds.swLng,
                bounds.swLat,
                bounds.neLng,
                bounds.neLat
            );
          }

          console.log('响应数据:', response.data);
          if (response.data.code === '200' && response.data.data) {
            const points = response.data.data;
            points.forEach(point => {
              this.addMarker(point.longitude, point.latitude, point.name, {
                pointId: point.pid
              });
            });
            ElMessage.success(`成功加载 ${points.length} 个点`);
          } else {
            ElMessage.warning('未找到点数据:' + response.data.message);
          }
        } catch (error) {
          console.error('错误详情:', error.response ? error.response.data : error.message);
          ElMessage.error('加载点数据失败: ' + error.message);
        } finally {
          this.loadingPoints = false;
        }
      } else {
        this.$emit('zoom-change', { zoom, clear: true });
      }
    },

    clearOverlays() {
      this.currentMarkers.forEach(marker => this.map.removeOverlay(marker));
      this.currentMarkers = [];
    },
    // 统一处理视图变化
    handleViewChange() {
      const zoom = this.map.getZoom();
      const bounds = this.getMapBounds();
      this.$emit('view-change', { zoom, bounds }); // 通知父组件
      this.handleZoomChange(); // 触发点更新逻辑
    },
    // 切换搜索面板显示
    toggleSearchPanel() {
      this.showSearchPanel = !this.showSearchPanel;
      this.suggestions = []; // 清空建议

      // 确保工具栏是展开状态
      if (this.showSearchPanel) {
        this.toolbarExpanded = true;
        this.showCoordinateInput = false; // 关闭坐标面板
      }
    },
  },

}
</script>

<style scoped>
.fullscreen-map {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

/* 地图容器 */
#map-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

/* 右侧工具栏 */
.toolbar {
  position: absolute;
  top: 50%;
  right: 0;
  transform: translateY(-50%);
  z-index: 1001;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px 0 0 16px;
  box-shadow: -4px 0 15px rgba(0, 0, 0, 0.15);
  padding: 15px 10px;
  display: flex;
  transition: all 0.3s ease;
}

.toolbar.collapsed {
  padding: 15px 5px;
  right: -40px;
}

.toolbar.collapsed .toolbar-content {
  display: none;
}

/* 修改工具栏折叠按钮位置 */
.collapse-btn {
  position: absolute;
  left: -30px; /* 调整这个值使按钮更靠近工具栏 */
  top: 50%;
  transform: translateY(-50%);
  width: 30px;
  height: 50px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 8px 0 0 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: -4px 0 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

/* 调整工具栏折叠状态时的位置 */
.toolbar.collapsed {
  padding: 15px 5px;
  right: 0; /* 减少这个值使折叠后工具栏更靠近可视区域 */
}

.collapse-btn:hover {
  background: #f0f2f5;
}

.collapse-btn .el-icon {
  font-size: 18px;
  transition: transform 0.3s ease;
}

.collapse-btn .rotated {
  transform: rotate(180deg);
}

.toolbar-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 22px;
  padding: 0 5px;
}

.user-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.user-info {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.username {
  font-size: 15px;
  font-weight: 600;
  color: #333;
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 工具按钮组 */
.tool-group {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.tool-group .el-button {
  width: 48px;
  height: 48px;
  font-size: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  margin: 0 auto;
}

.tool-group .el-button:hover {
  transform: scale(1.12);
}

.tool-group .el-button:active {
  transform: scale(0.95);
}

.tool-group .el-button.el-button--danger {
  background-color: #ff4d4f;
  color: white;
}

.tool-group .el-button.el-button--danger:hover {
  background-color: #ff7875;
}

/* 坐标输入面板 - 显示在工具栏左侧，固定在指定位置 */
.coordinate-panel {
  position: absolute;
  top: v-bind(coordinatePanelTop); /* 使用绑定值 */
  right: 100px;
  transform: translateY(-50%);
  z-index: 1002; /* 确保在工具栏上方 */
  background: rgba(255, 255, 255, 0.97);
  border-radius: 12px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  padding: 18px;
  width: 240px;
  transition: opacity 0.3s ease, transform 0.3s ease;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  font-weight: 600;
  font-size: 17px;
  color: #333;
}

.panel-content {
  display: flex;
  flex-direction: column;
  gap: 14px;
}

.panel-content .el-input {
  width: 100%;
}

.set-center-btn {
  margin-top: 12px;
  height: 38px;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(10px) translateX(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0) translateX(0);
  }
}
</style>

<style>
/* 全局对话框样式 */
.logout-dialog {
  background-color: rgba(0, 0, 0, 0.6);
  z-index: 2000 !important;
}

.logout-dialog .el-dialog {
  background: rgba(255, 255, 255, 0.97);
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  overflow: hidden;
}

.logout-dialog .el-dialog__header {
  padding: 22px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
  background: rgba(240, 243, 247, 0.8);
}

.logout-dialog .el-dialog__title {
  font-weight: 700;
  color: #333;
  font-size: 19px;
}

.logout-dialog .el-dialog__body {
  padding: 28px 22px;
  font-size: 16px;
  color: #555;
  text-align: center;
}

.logout-dialog .el-dialog__footer {
  padding: 18px 22px 22px;
  text-align: center;
}

.logout-dialog .el-button {
  min-width: 100px;
  height: 40px;
  font-size: 15px;
  border-radius: 8px;
}
.search-panel {
  position: absolute;
  top: 40%; /* 放在比坐标面板稍高的位置 */
  right: 100px;
  transform: translateY(-50%);
  z-index: 1002;
  background: rgba(255, 255, 255, 0.97);
  border-radius: 12px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  padding: 18px;
  width: 300px; /* 比坐标面板稍宽 */
}

.panel-content {
  position: relative;
}

/* 搜索建议样式 */
.suggestions {
  position: absolute;
  width: 100%;
  max-height: 200px;
  overflow-y: auto;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  z-index: 1003;
  margin-top: 5px;
}

.suggestion-item {
  padding: 8px 12px;
  cursor: pointer;
  font-size: 14px;
}

.suggestion-item:hover {
  background-color: #f5f7fa;
}
</style>
